#include <QApplication>
#include <QFuture>
#include <QDebug>
#include <QtConcurrentMap>
#include <QVector>
#include <cmath>

const double PI = std::atan(1.0)*4;

struct chunk {
    double x1;
    double x2;
};

double func(double x) {
    return sin(x);
}

double map(const chunk& c) {
    return (func(c.x1) + func(c.x2)) / 2 * (c.x2 - c.x1);
}

void reduce(double & result, const double& chunkArea) {
    result += chunkArea;
}


int main() {
    double start = 0;
    double end = PI;
    int intervals = 100;

    QVector<chunk> chunks;

    for (int i = 0; i < intervals; ++i) {
        chunk* c = new chunk;
        c->x1 = (end-start)/intervals * i;
        c->x2 = (end-start)/intervals * (i+1);
        chunks.push_back(*c);
    }

    QFuture<double> integralValue = QtConcurrent::mappedReduced(chunks, map, reduce);
    integralValue.waitForFinished();

    qDebug() << "Answer: " << integralValue;
}
